﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Game
{
    class Solution
    {

        Random _rand = new Random();
        List<int> _order;
        int _solution;
        public int Fitness
        {
            get { return _solution; }
            set { _solution = value; }
        }
        public Solution(int size)
        {
            _order = new List<int>(size);
            for (int i = 0; i < _order.Capacity; i++) _order.Add(i);
            //use Fisher –Yates shuffle algorithm
            for (int i = _order.Count - 1; i >= 0; i--)
            {
                int j = _rand.Next(i + 1);
                int temp = _order[i];
                _order[i] = _order[j];
                _order[j] = temp;
            }           
        }
        public Solution(List<int> order)
        {            
            _order = order;
        }
        public List<int> Order {
            get { return _order; }
        }
        public Solution CrossOver(Solution other)
        {
            List<int> temp = new List<int>(_order.Count);
            for (int i = 0; i < temp.Capacity; i++)
            {
                temp.Add(-1);
            }

            int head = _rand.Next(_order.Count() / 2);
            int tail = _rand.Next(_order.Count() / 2) + _order.Count() / 2;
            for (int i = head; i < tail; i++)
            {
                temp[i] = _order[i];
            }
            int index = 0;
            for (int i = 0; i < other._order.Count; i++)
            {
                int tt = other._order[i];

                if (!temp.Contains(tt))
                {
                    while (index < temp.Count && temp[index] != -1)
                    {
                        index++;
                    }
                    temp[index] = tt;
                }
            }
            return new Solution(temp);
        }
        public void Mutation()
        {
            int head = _rand.Next(_order.Count / 2);
            int tail = _rand.Next(_order.Count / 2) + (_order.Count / 2);
            int value = _order[tail];
            _order.RemoveAt(tail);
            _order.Insert(head, value);
        }
        
    }
}
